var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken')
var multiparty = require('multiparty');


const tencentcloud = require("tencentcloud-sdk-nodejs-iai")
const SMSClient = require('@alicloud/sms-sdk'); // 引入阿里云 SDK
let list = [
  { id: 1, username: 'niuxiao', name: '牛晓', password: 'admin123', tel: "", imgsrc: 'https://preview.qiantucdn.com/freepik/free-photo/51317735.jpg!w1024_new_small_1' },
  { id: 2, username: 'shuaizhuang', name: '李帅壮', password: 'admin123', imgsrc: 'https://img.yzcdn.cn/vant/cat.jpeg' },
  { id: 3, username: 'goukang', name: '杨子康', password: 'admin123', imgsrc: 'https://preview.qiantucdn.com/freepik/free-photo/selective-focus-shot-of-a-black-labrador-retriever_181624-58233.jpg!w1024_new_small_1' },
  { id: 4, username: 'fanjiaping', name: '范佳平', password: 'admin123', tel: '18931057279', imgsrc: 'https://www.hzl6.com/uploadfile/2023/0511/202305111683787380976517.jpg' },
]

router.post("/update", async function (req, res, next) {
  let { phone, password } = req.body;
  let data = list.filter(item => item.tel == phone);
  if (data) {
    await lissmodel.update({ _id: data._id }, {
      password:
        password
    });
  } else {
    res.send({
      code: 401,
      msg: "用户不存在"
    })
  }
})




//图片上传
router.post('/img', (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = 'upload'
  form.parse(req, (err, fields, files) => {
    console.log(files);
    res.send({
      code: 200,
      msg: '上传成功',
      data: files.avatar[0].path
    })
  })
})

// 登录图片接口
router.post('/loginimg', (req, res) => {
  let user = req.body.user
  const filteredUsers = list.filter(item => item.username === user);
  console.log(filteredUsers[0]);
  if (filteredUsers[0]) {
    res.send({
      data: filteredUsers[0].imgsrc,
    })

  }
  return false

})
//注册
router.post('/register', async (req, res) => {
  console.log(req.body);
  let { username, password, tel } = req.body.value
  let img = req.body.img
  list.push({ username: username, password: password, tel: tel, img: img })
  console.log(list);
  res.send({
    code: 200,
  })
})
//账号登录
router.post('/login', async (req, res) => {
  let { user, pwd } = req.body
  console.log(user, pwd);
  const filteredUsers = list.filter(item => item.username === user && item.password === pwd);
  if (filteredUsers[0]) {
    let accessToken = jwt.sign({ users: 'niu' }, "face", { expiresIn: '3s' })
    let token = jwt.sign({ users: filteredUsers[0].username, pwd: filteredUsers[0].password }, "face", { expiresIn: '1d' })
    res.send({
      code: 200,
      data: filteredUsers[0],
      token: token,
      accessToken: accessToken
    })
  } else {
    res.send({
      code: 400,
      msg: '账号密码错误'
    })
  }
})

//人脸识别接口
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64

  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: "AKIDKgwgEamoeJm5D90gBUcYotmU1OaLTQWP",
      //自己的腾讯密匙
      secretKey: "pTxFRTL3b0DF6lFYffv1mU0JRM5bu0uc",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "fanjiaping"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };

  let doc = await client.SearchFaces(params)

  //doc为人脸识别后的返回信息
  console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    console.log(personName, 'personNume');
    const filteredUsers = list.filter(user => user.name === personName);
    //生成token
    let token = jwt.sign({ users: filteredUsers[0].username }, "face", { expiresIn: '1d' })
    let accessToken = jwt.sign({ users: 'niu' }, "face", { expiresIn: '3s' })
    res.send({
      code: 200,
      msg: "登录成功！",
      data: filteredUsers[0],
      token,
      accessToken
    })

  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }

})
//phone
router.post('/phone', (req, res) => {
  let phone = req.body.phone
  const filteredUsers = list.filter(item => item.tel === phone);
  let token = jwt.sign({ users: filteredUsers[0].username }, "face", { expiresIn: '1d' })
  let accessToken = jwt.sign({ users: 'niu' }, "face", { expiresIn: '3s' })
  res.send({
    code: 200,
    data: filteredUsers[0],
    token: token,
    accessToken: accessToken
  })
})
//短信认证
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
    str += parseInt(Math.random() * 10)
  }
  return str;
}
//手机号验证码
let msm = ''
router.post('/get_sms', function (req, res) {
  console.log(req.body);
  let phoneNum = req.body.phone;
  console.log(phoneNum);

  //获取前端参数phone
  console.log("手机号码", phoneNum);

  //初始化sms_client
  let smsClient = new SMSClient({
    accessKeyId: 'LTAI5tLaXC2qMPwZdHTdCxvn',  //accessKeyId 前面提到要准备的
    secretAccessKey: 'uUC6druFdqSJfHW979RDMXUy9kExGv'  //secretAccessKey 前面提到要准备的
  });
  let str = getCode();
  msm = str;
  // 开始发送短信
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: "装修测量系统", //签名名称 前面提到要准备的
    TemplateCode: "SMS_474801206", //模版CODE  前面提到要准备的
    TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，send格式
  }).then(result => {
    console.log("result", result)
    let { Code } = result;
    if (Code == 'OK') {
      res.send({
        code: 0,
        msg: 'success',
        sms: str
      })
      console.log(result)
    }
  }).catch(err => {
    console.log(err);
    res.send({
      code: 1,
      msg: 'fail: ' + err.data.Message
    })
  })
});

module.exports = router;
